﻿using DDD.Core.Const;
using DDD.Core.DependencyInjection;
using DDD.Domain.Repositories;
using FluentValidation;

namespace DDD.Application.Commands.UserCommand.CreateUser
{
    public class CreateUserCommandValidate : AbstractValidator<CreateUserCommand>
    {
        public CreateUserCommandValidate()
        {
            RuleFor(c => c.Password).NotEmpty()
                .NotNull().MinimumLength(5);

            RuleFor(c => c.UserName).NotEmpty()
            .NotNull().MinimumLength(5)
            .Must(c => BeUniqueUserName(c)).WithMessage(c => $"用户名：{c.UserName}已经被注册");

            RuleFor(c => c.Email).NotNull().When(c => !string.IsNullOrEmpty(c.Email))
                .Matches(RegexConst.EMAIL);

            RuleFor(c => c.Phone).NotNull().When(c => !string.IsNullOrEmpty(c.Phone))
                .Matches(RegexConst.PHONE);
        }

        private bool BeUniqueUserName(string username)
            => IOC.Resolve<IUserRepository>().Query(c => c.UserName == username).FirstOrDefault() == null;
    }
}
